﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.BusinessLogic.Entities;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.UI.Common.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Events;

namespace DiscoveryLogic.Analytics.Modules.Entities
{
	public class PersonListPresenter
	{
		private PersonListView _View;
		/// <summary></summary>
		public PersonListView View
		{
			get
			{
				return this._View;
			}
			set
			{
				this._View = value;
				if(this._View !=null)
				{
					this._View.PersonSelected += new PersonListView.OnPersonSelected(SelectPerson);
					this._View.Persons = this.ReadPersonList();
				}
			}
		}

		private readonly IEventAggregator _EventAggregator;
        private SubscriptionToken _SubscriptionToken;

		public PersonListPresenter(IEventAggregator eventAggregator)
		{
			this._EventAggregator = eventAggregator;
		}

		public void SelectPerson(PersonDO person)
		{
			if(person !=null)
			{
				this._EventAggregator.GetEvent<PersonSelectedEvent>().Publish(person);
			}
		}

        public void RegisterPersonSelectionChangedEventHandler(PersonDO person)
        {
            PersonSelectedEvent personSelectedEvent =
                    _EventAggregator.GetEvent<PersonSelectedEvent>();
            if (this._SubscriptionToken != null)
            {
                personSelectedEvent.Unsubscribe(_SubscriptionToken);
            }
            this._SubscriptionToken = personSelectedEvent.Subscribe(
                PersonSelectedHandler,
                ThreadOption.UIThread,
                false);
        }

        private void PersonSelectedHandler(PersonDO person)
        {
            this._View.SelectPerson(person);
        }

		private List<PersonDO> ReadPersonList()
		{
		    return EntityManager.GeneratePersonsForTest();
		}
	}
}
